package mk.com.ldm.corepoint.administration.client;

import mk.com.ldm.corepoint.administration.client.event.ModalEvent;
import mk.com.ldm.corepoint.administration.client.event.ModalEventHandler;
import mk.com.ldm.corepoint.administration.client.presenter.EditPresenter;
import mk.com.ldm.corepoint.administration.client.presenter.LoginPresenter;
import mk.com.ldm.corepoint.administration.client.presenter.MainPresenter;
import mk.com.ldm.corepoint.administration.client.presenter.Presenter;
import mk.com.ldm.corepoint.administration.client.view.EditView;
import mk.com.ldm.corepoint.administration.client.view.LoginView;
import mk.com.ldm.corepoint.administration.client.view.MainView;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;

public class AppController implements Presenter, ValueChangeHandler<String> {
  private final HandlerManager eventBus;
  private final CoreServiceAsync rpcService; 
  private HasWidgets container;
  
    
  public AppController(CoreServiceAsync rpcService, HandlerManager eventBus) {
    this.eventBus = eventBus;
    this.rpcService = rpcService;
    bind();
  }
  
  private void bind() {
    History.addValueChangeHandler(this);
    
    eventBus.addHandler(ModalEvent.TYPE, new ModalEventHandler(){

		public void onModal(ModalEvent event) {
			launchWindow(event.getType(), event.getId());
		}
    	
    });
    
  }
  
  public void go(final HasWidgets container) {
    this.container = container;
    
    if ("".equals(History.getToken())) {
      History.newItem("login");
    }
    else {
      History.fireCurrentHistoryState();
    }
  }

  
  
  public void onValueChange(ValueChangeEvent<String> event) {
    String token = event.getValue();
    
    

    if (token != null) {
      Presenter presenter = null;

      if (token.equals("login")) {
        presenter = new LoginPresenter(rpcService, eventBus, new LoginView());
      } else
      if (token.equals("main")) {
    	presenter = new MainPresenter(rpcService, eventBus, new MainView());
      }
      
      if (presenter != null) {
        presenter.go(container);
      }
    }
  } 
 
  public void launchWindow(String type, String id){
	  Presenter presenter;
	  presenter = new EditPresenter(rpcService, eventBus, new EditView(type,id));
	  presenter.go(container);
  }
  

  
}
